<template>
  <div class="page-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input v-model="searchForm.deptName" placeholder="请输入部门名称" style="width: 200px; margin-right: 10px" />
      <el-input v-model="searchForm.leader" placeholder="请输入负责人" style="width: 200px; margin-right: 10px" />
      <el-input v-model="searchForm.phone" placeholder="请输入联系电话" style="width: 200px; margin-right: 10px" />
      <el-button type="primary" @click="loadData">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="handleAdd" style="margin-right: 10px">
        添加部门
      </el-button>
    </div>

    <!-- 表格 -->
    <el-card class="table-card" shadow="never" :loading="loading">
      <el-table :data="tableData" border style="width: 100%" :header-cell-style="{
        background: '#f5f7fa',
        color: '#606266',
        fontWeight: 'bold',
        height: '50px',
      }" :cell-style="{
          padding: '12px 0',
        }">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="deptName" label="部门名称" min-width="120" align="center" />
        <el-table-column prop="leader" label="负责人" min-width="120" align="center" />
        <el-table-column prop="phone" label="联系电话" min-width="120" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
              @change="(val: number) => handleStatusChange(scope.row.id, val)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加部门' : '编辑部门'" width="500px"
      @close="handleClose">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="form.deptName" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import {
  pageRequest,
  addRequest,
  editRequest,
  delRequest,
  updateStatus,
} from "../../api/dept"

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  deptName: "",
  leader: "",
  phone: "",
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref("add")
const formRef = ref()
const form = reactive({
  id: "",
  deptName: "",
  leader: "",
  phone: "",
  status: 1,
})

// 表单校验规则
const rules = {
  deptName: [
    { required: true, message: "请输入部门名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  leader: [
    { required: true, message: "请输入负责人", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
}

// 加载表格数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      ...searchForm,
    }
    const res: any = await pageRequest(params)
    if (res.code === 200) {
      tableData.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error("加载数据失败:", error)
    ElMessage.error("加载数据失败")
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.deptName = ""
  searchForm.leader = ""
  searchForm.phone = ""
  currentPage.value = 1
  loadData()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 清空表单
const resetForm = () => {
  form.id = ""
  form.deptName = ""
  form.leader = ""
  form.phone = ""
  form.status = 1
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 添加部门
const handleAdd = () => {
  dialogType.value = "add"
  dialogVisible.value = true
  resetForm()
}

// 编辑部门
const handleEdit = (row: any) => {
  dialogType.value = "edit"
  dialogVisible.value = true
  resetForm()
  Object.assign(form, row)
}

// 删除部门
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该部门吗？删除后不可恢复！", "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(async () => {
      try {
        await delRequest(row.id)
        ElMessage.success("删除成功")
        loadData()
      } catch (error: any) {
        console.error("删除失败:", error)
        ElMessage.error(error.response?.data?.msg || "删除失败")
      }
    })
    .catch(() => { })
}

// 更新部门状态
const handleStatusChange = async (id: number, status: number) => {
  try {
    await updateStatus(id, status)
    ElMessage.success("状态更新成功")
    loadData()
  } catch (error) {
    console.error("状态更新失败:", error)
    ElMessage.error("状态更新失败")
    loadData() // 更新失败时重新加载数据，恢复原状态
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        if (dialogType.value === "add") {
          await addRequest(form)
          ElMessage.success("添加成功")
        } else {
          await editRequest(form)
          ElMessage.success("编辑成功")
        }
        dialogVisible.value = false
        loadData()
      } catch (error: any) {
        console.error("操作失败:", error)
        ElMessage.error(error.response?.data?.msg || "操作失败")
      } finally {
        loading.value = false
      }
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  height: 100%;
  background-color: #f5f7fa;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

:deep(.el-card__body) {
  padding: 0;
}

:deep(.el-table) {
  border-radius: 4px;
}
</style>
